from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from sqlalchemy import text
from app.database import engine, get_db, Base, SessionLocal
from app.models import User, Spot, Order
from app.api import auth, spots, orders, favorites, users, admin
from app.db.seeds import seed_spots, seed_admin
from sqlalchemy import inspect
from app.core.scheduler import init_scheduler

app = FastAPI(title="Tourism System API")

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 创建数据库表（如果不存在）
@app.on_event("startup")
async def startup_event():
    # 只创建不存在的表，不会删除现有数据
    Base.metadata.create_all(bind=engine)
    # 初始化数据
    db = SessionLocal()  # 直接使用 SessionLocal() 而不是 get_db()
    try:
        seed_admin(db)  # 创建管理员账号
        seed_spots(db)  # 创建示例景点
    finally:
        db.close()
    # 初始化定时任务
    init_scheduler()

# 包含路由
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
app.include_router(spots.router, prefix="/api/spots", tags=["spots"])
app.include_router(orders.router, prefix="/api/orders", tags=["orders"])
app.include_router(favorites.router, prefix="/api/favorites", tags=["favorites"])
app.include_router(users.router, prefix="/api/users", tags=["users"])
app.include_router(admin.router, prefix="/api/admin", tags=["admin"])

@app.get("/")
async def root():
    return {"message": "Welcome to Tourism System API"}

@app.get("/test-db")
async def test_db(db: Session = Depends(get_db)):
    try:
        # 测试数据库连接
        db.execute(text("SELECT 1"))
        return {"message": "Database connection successful!"}
    except Exception as e:
        return {"error": f"Database connection failed: {str(e)}"} 